﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using mal.balades.Business.DataModel;
using mal.balades.Business.Log;
using mal.balades.Business.Web;
using mal.Web.Routing;
using mal.balades.Business.Helper;


namespace mal.balades.Web.Views
{
    public partial class VisitView : PageBase
    {
        private const string CategoryIdKey = "catId";
        private const string CategoryUrlNameKey = "catUrl";
        private const string VisitIdKey = "VisitId";
        private const string VisitUrlNameKey = "VisitUrl";
        private const string VisitCatUrlNameKey = "VisitCatUrl";

        private string CategoryUrlName = string.Empty;
        private int VisitId = int.MinValue;
        private string visitUrlName = string.Empty;
        private List<Picture> pictures;

        protected Visit visit;

        public string VisitUrlName
        {
            get
            {
                if (visit != null)
                    return visit.UrlName;
                else
                    return string.Empty;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            JavascriptHelper javascriptHelper = new JavascriptHelper(System.Web.UI.ScriptManager.GetCurrent(this));
            javascriptHelper.BuildScript("/Scripts/VisitView");
            
            CheckRequest();

            if (visit == null)
            {
                Response.End();
            }
            else
            {
                this.Title = visit.Title;

                visit.Text = HtmlFormatVisitLink.Format(visit.Text.Replace("\"", string.Empty));
                this.metaDescription.Attributes["content"] = visit.SumUp;

                foreach (Information item in visit.Informations)
                {
                    item.Text = HtmlFormatVisitLink.Format(item.Text);
                }

                //this.imgPlaceCat.ImageUrl = CategoryPictureUrl(visit.PlaceCategory.Image);
                //this.hlPlaceCat.NavigateUrl = CategoryUrl(visit.PlaceCategory.UrlName);
                //this.hlPlaceCat.ToolTip = visit.PlaceCategory.Name;
                this.placeCat.NavigateUrl = CategoryUrl(visit.PlaceCategory.UrlName);
                this.placeCat.Text = visit.PlaceCategory.Name;


                //this.imgMarketCat.ImageUrl = CategoryPictureUrl(visit.MarketingCategory.Image);
                //this.hlMarketCat.NavigateUrl = CategoryUrl(visit.MarketingCategory.UrlName);
                //this.hlMarketCat.ToolTip = visit.MarketingCategory.Name;
                this.marketCat.Text = visit.MarketingCategory.Name;
                this.marketCat.NavigateUrl = CategoryUrl(visit.MarketingCategory.UrlName);


                advantages.DataSource = BaladesManager.GetVisitInformations(visit, InformationType.InformationTypeValue.Advantage);
                advantages.DataBind();

                inconveniences.DataSource = BaladesManager.GetVisitInformations(visit, InformationType.InformationTypeValue.Inconvenience);
                inconveniences.DataBind();

                advices.DataSource = BaladesManager.GetVisitInformations(visit, InformationType.InformationTypeValue.Advise);
                advices.DataBind();

                pictures = BaladesManager.GetVisitPictures(visit, PictureType.PictureTypeValue.Picture).ToList();

                ClientScript.RegisterStartupScript(this.GetType(), this.ToString(), JsSerializePictures(pictures), true);


                //visitPicturesScript.DataSource = pictures;
                //visitPicturesScript.DataBind();

                // dlPictures.DataSource = pictures;
                // dlPictures.DataBind();

                DisplayCoordonates();

                IEnumerable<VisitList> closedVisits = BaladesManager.GetClosedVisits(visit.VisitID);

                if (closedVisits.Count() > 0)
                {

                    List<MapVisitList> results = new List<MapVisitList>();

                    foreach (VisitList visitList in closedVisits)
                    {
                        results.Add(new MapVisitList(visitList));
                    }

                    rptClosedVists.DataSource = results.OrderBy(v => v.Distance);
                    rptClosedVists.DataBind();
                    closedVisitsTab.Visible = true;
                }
                else
                {
                    closedVisitsTab.Visible = false;
                }

                IEnumerable<Feed> feeds = BaladesManager.FeedDataAccess.GetVisitFeeds(visit);

                if (feeds.Count() > 0)
                {
                    rptFeeds.DataSource = feeds;
                    rptFeeds.DataBind();
                    feedsPanel.Visible = true;
                    feedTab.Visible = true;
                }
                else
                {
                    feedsPanel.Visible = false;
                    feedTab.Visible = false;
                }

                visitTab.Visible = true;

                headerImage.ImageUrl = VisitPictureUrl(pictures[0].Url);
            }

        }

        protected void CheckRequest()
        {
            MalLogManager.WebLogger.Info("");
            if (Request[VisitIdKey] != null)
            {
                int.TryParse(Request[VisitIdKey], out VisitId);
            }

            if (PageRouteHandler.QueryString[VisitIdKey] != null)
            {
                int.TryParse(PageRouteHandler.QueryString[VisitIdKey].ToString(), out VisitId);
            }


            if (Request[VisitUrlNameKey] != null)
            {
                visitUrlName = Request[VisitUrlNameKey];
            }

            if (Request[VisitCatUrlNameKey] != null)
            {
                visitUrlName = Request[VisitCatUrlNameKey];

                string[] arrTmp = visitUrlName.Split("/".ToCharArray());

                if (arrTmp.Length == 2)
                    visitUrlName = arrTmp[1];
            }

            if (PageRouteHandler.QueryString[VisitUrlNameKey] != null)
            {
                visitUrlName = PageRouteHandler.QueryString[VisitUrlNameKey].ToString();
            }

            if (VisitId != int.MinValue)
            {
                MalLogManager.WebLogger.InfoFormat("VisitId:{0}", VisitId);
                visit = BaladesManager.GetVisit(VisitId);
            }
            else if (!string.IsNullOrEmpty(visitUrlName))
            {
                MalLogManager.WebLogger.InfoFormat("visitUrlName:{0}", visitUrlName);
                visit = BaladesManager.GetVisit(visitUrlName);
            }
        }

        public string JsSerializePictures(List<Picture> pictures)
        {
            StringBuilder js = new StringBuilder();

            js.AppendFormat("function InitializeSlideShow()\n{{\n");
            js.AppendFormat("SlideShowInitialized=true;\n");
            for (int i = 0; i < pictures.Count; i++)
            {
                Picture picture = pictures[i];
                js.AppendFormat("AddPicture(\"{0}\",\"{1}\");\n", picture.Title, VisitPictureUrl(picture.Url));
            }

            js.AppendFormat("}}\n");
            return js.ToString();
        }

        public string FormatText(string text)
        {
            string formatedText = text.Replace("\n", "<br />");
            formatedText = formatedText.Replace(". ", ".<br />");

            return formatedText;
        }

        protected void DisplayCoordonates()
        {
            if (visit.Latitude.HasValue && visit.Longitude.HasValue)
            {
                this.visitCoordinates.Visible = true;

                this.coordonates.Text = string.Format("{0} {1}"
                    , Math.Round(visit.Latitude.Value, 5), Math.Round(visit.Longitude.Value, 5));
            }
            else
            {
                this.visitCoordinates.Visible = false;
            }


        }

        public string BuildJavascript()
        {
            StringBuilder js = new StringBuilder();

            js.AppendFormat("var visitID = {0};\n", visit.VisitID);
            js.AppendLine("function initializeData(){");

             foreach (Picture picture in this.pictures)
            {
                js.AppendFormat("viewModel.addPicture({0},'{1}','{2}');\n"
                    , picture.PictureID, VisitPictureUrl(picture.Url), FormatJavascriptString(picture.Title));
            }
            js.AppendLine("}");
            return js.ToString();
        }

        private string FormatJavascriptString(string text)
        {
            string result = text;
            result = result.Replace("'", "\\'");

            return result;
        }
    }
}